﻿#include "FileDialogWidget.h"
#include <QApplication>
#include <QWidget>
#include <QVBoxLayout>
#include <QPushButton>
#include <QLineEdit>
#include <QFileDialog>
#include <QMimeData>
#include <QUrl>
#include <QDebug>

FileDialogWidget::FileDialogWidget(void)
{
    QFont font("微软雅黑", 12);
    lineEdit = new QLineEdit(&box);
    but_open = new QPushButton("打开文件", &box);
    but_ctr = new QPushButton("  ", &box);
    box.resize(800, 45);
    lineEdit->move(5, 5);
    lineEdit->resize(595, 35);
    lineEdit->setFont(font);
    lineEdit->setAcceptDrops(true); // 允许拖放操作
    lineEdit->clear();
    but_open->move(605, 5);
    but_open->resize(75, 35);
    but_open->setFont(font);
    but_ctr->move(685, 5);
    but_ctr->resize(75, 35);
    but_ctr->setFont(font);
    but_ctr->setEnabled(false);
    connect(but_open, &QPushButton::clicked, this, &FileDialogWidget::openFileDialog);
    connect(but_ctr, &QPushButton::clicked, this, &FileDialogWidget::but_ctr_sloot);
}

FileDialogWidget::~FileDialogWidget()
{
    delete (but_open);
    but_open = NULL;
    delete (lineEdit);
    lineEdit = NULL;
}

void FileDialogWidget::set(QWidget *parent, int x, int y, const char *str, const char *bot_name)
{
    box.setParent(parent);     // 设置父窗口
    box.move(x, y);

    if (str != NULL)
    {
        lineEdit->setText(QString::fromUtf8(str));
    }

    if (bot_name != NULL)
    {
        but_ctr->setText(QString::fromUtf8(bot_name));
    }
}

bool FileDialogWidget::is_path(void)
{
    if (get_path().length() < 3)
    {
        return false;
    }

    QFileInfo fileInfo(get_path());
    QString path = fileInfo.absolutePath();// 提取路径部分
    QDir dir(path);  // 替换为你要遍历的目录路径

    if (dir.exists())
    {
        return true;
    }

    return false;
}

QString FileDialogWidget::get_path(void)
{
    return lineEdit->text();
}

void FileDialogWidget::openFileDialog()
{
    QString filePath = QFileDialog::getOpenFileName(this, "Open File", "", "All Files (*.*)");

    if (!filePath.isEmpty())
    {
        lineEdit->setText(filePath);
        bool path_en = is_path();
        emit path_Signal(path_en);  // 发射信号
        but_ctr->setEnabled(path_en);
    }
}

void FileDialogWidget::but_ctr_sloot()
{
    if (is_path())
    {
        emit ctrl_Signal();  // 发射信号
    }
}
